package com.quik.web.product.action;

import java.nio.charset.Charset;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.quik.common.Constants;
import com.quik.dto.PaginationDto;
import com.quik.entity.DtaProductCategory;
import com.quik.entity.DtaProductSubCategory;
import com.quik.entity.SysAccount;
import com.quik.exception.ErrorCode;
import com.quik.web.product.service.ProductService;

/**
 * 功能说明：
 *         产品的商品分类控制 
 * @author Jenny
 *
 */
@Controller
@RequestMapping("/productCategory")
public class ProductCategoryCotroller {
	
	private static Logger log = (Logger)Logger.getLogger(ProductCategoryCotroller.class);
	
	@Autowired
	private ProductService productService;
	
	/**
	 * 进入产品分类列表界面
	 * @return
	 */
	@RequestMapping(value = "productCategoryList", method = RequestMethod.GET)
	public String productCategoryList(){
		return "/product/category/categoryList";
	}

	/**
	 * 根据条件查询商品分类（分页）
	 * @param page
	 * @param rows
	 * @param categoryName
	 * @return
	 */
	@RequestMapping(value = "queryCategory", method = RequestMethod.POST)
	@ResponseBody
	public PaginationDto queryCategory(Integer page, Integer rows, String categoryName){
		PaginationDto dto = new PaginationDto(0, null);
		
		try{
			int intPage = (page == null || page == 0) ? 1:page;  //当前页
		    int pageSize = (rows == null || rows == 0) ? Constants.TREE_PAGE_SIZE : rows;  //每页显示的记录
			
		    int totalCount = productService.findCategoryCount(categoryName);  //总记录数
			
			List list = productService.findCategory(categoryName, intPage, pageSize);
			
		    dto.setRows(list);
		    dto.setTotal(totalCount);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ProductCategoryCotroller queryCategory error: " + e.getMessage());
		}
		
		return dto; 
	}
	
	/**
	 * 进入新增商品类别界面
	 * @return
	 */
	@RequestMapping(value = "initAddCategory", method = RequestMethod.GET)
	public ModelAndView initAddCategory(){
		ModelAndView mav = new ModelAndView("/product/category/addCategory");
		
		try{
			List categoryList = productService.findCategory();
			mav.addObject("categoryList", categoryList);
		}catch(Exception e){
			e.printStackTrace();
			log.error("ProductCategoryCotroller initAddCategory error: " + e.getMessage());
		}
		
		return mav;
	}
	
	/**
	 * 新增商品类别
	 * 	   1.检查商品类别是否同名
	 *     2.新增
	 * @param category
	 * @return
	 */
	@RequestMapping(value = "addCategory", method = RequestMethod.POST)
	public ResponseEntity<String> addCategory(DtaProductCategory category, HttpServletRequest request){
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
		String result = ErrorCode.RESULT_ADD_CATEGORY_FAILED;
		
		//解决返回中文乱码问题
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
        headers.setContentType(mediaType);     
        
		try{
			boolean isExist = productService.isExistCategory(category.getProduct_category_name());
			if(isExist)
				result = ErrorCode.RESULT_ADD_CATEGORY_FAILED_EXIST;
			else{
				category.setCrt_user(account.getStaff_no());
				category.setCrt_date(new java.util.Date(System.currentTimeMillis()));
			
				productService.addCategory(category);
				result = "success";
			}
			
		}catch(Exception e){
			e.printStackTrace();
			result = ErrorCode.SYSTEM_ERROR;
		}
		
		return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
	
	/**
	 * 新增商品子类
	 * 	   1.检查同一大类下商品子类是否同名
	 *     2.新增
	 * @param category
	 * @return
	 */
	@RequestMapping(value = "addSubCategory", method = RequestMethod.POST)
	public ResponseEntity<String> addSubCategory(DtaProductSubCategory subCategory, HttpServletRequest request){
		SysAccount account = (SysAccount)request.getSession().getAttribute(Constants.SESSION_ACCOUNT);
		String result = ErrorCode.RESULT_ADD_SUB_CATEGORY_FAILED_EXIST;
		
		//解决返回中文乱码问题
		HttpHeaders headers = new HttpHeaders(); 
		MediaType mediaType=new MediaType("text","html",Charset.forName("UTF-8"));     
        headers.setContentType(mediaType); 
		
		try{
			boolean isExist = productService.isExistSubCategory(subCategory.getProduct_sub_category_name(), 
						subCategory.getProduct_category_id());			
			if(isExist)
				result = ErrorCode.RESULT_ADD_SUB_CATEGORY_FAILED_EXIST;
			else{
				subCategory.setCrt_user(account.getStaff_no());
				subCategory.setCrt_date(new java.util.Date(System.currentTimeMillis()));
			
				productService.addSubCategory(subCategory);
				result = "success";
			}
			
		}catch(Exception e){
			e.printStackTrace();
			result = ErrorCode.SYSTEM_ERROR;
		}
		
		return new ResponseEntity<String>(result, headers, HttpStatus.OK);
	}
	
	/**
	 * 查询商品大类
	 * @return
	 */
	@RequestMapping(value = "getCategorySel", method = RequestMethod.POST)
	@ResponseBody
	public List getCategorySel(){
		List list = null;
		
		try{
			list = productService.findCategory();
			
		}catch(Exception e){
			e.printStackTrace();
			log.error("ProductCategoryCotroller getCategorySel error: " + e.getMessage());
		}
		
		return list;
	}
}
